package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void insert(String keyword,Integer userId) {

        if(StringUtils.isNotBlank(keyword)){
            //判断是否已经输入过
            Query query = Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId).and("isDeleted").is(0));  //两条件
            ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
            if(apUserSearch!=null){
                apUserSearch.setCreatedTime(new Date());
                mongoTemplate.save(apUserSearch);
            }else{
                apUserSearch =new ApUserSearch();
                apUserSearch.setUserId(userId);
                apUserSearch.setKeyword(keyword);
                apUserSearch.setCreatedTime(new Date());
                mongoTemplate.save(apUserSearch);
            }
        }

    }

    @Override
    public ResponseResult findUserSearch() {
        Query query = Query.query(Criteria.where("userId").is(ThreadLocalUtil.getUserId()).and("isDeleted").is(0))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        query.limit(10);
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }


    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
//        Query query = Query.query(Criteria.where("id").is(dto.getId()));
//        mongoTemplate.remove(query,ApUserSearch.class);
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
       // Query query = Query.query(Criteria.where("id").is(dto.getId()));
        ApUserSearch apUserSearch = mongoTemplate.findById(dto.getId(), ApUserSearch.class);
        if(apUserSearch!=null){
            apUserSearch.setIsDeleted(1);
            mongoTemplate.save(apUserSearch);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
